package com.mimc.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.mimc.common.exception.ServiceException;
import com.mimc.common.utils.ip.IpUtils;
import com.mimc.core.model.SysMenu;
import com.mimc.core.model.SysUserRole;
import com.mimc.core.service.SysRoleMenuService;
import com.mimc.core.service.SysUserRoleService;
import com.mimc.framework.jwt.AdminTokenUtils;
import io.jboot.Jboot;
import io.jboot.aop.annotation.Bean;
import io.jboot.aop.annotation.ConfigValue;
import io.jboot.db.model.Columns;

import java.util.Date;
import java.util.List;

@Bean
public class ShSysAdminService {
    @ConfigValue("yminfo.md5key")
    private String md5Key;
    @Inject
    private SysUserRoleService sysUserRoleService;
    @Inject
    private SysRoleMenuService sysRoleMenuService;
    public String login(String username,String password){
        if(StrUtil.isBlank(username)){
            throw new ServiceException("请输入用户名");
        }
        if(StrUtil.isBlank(password)){
            throw new ServiceException("请输入密码");
        }
        Record admin= Db.findFirst("select * from sys_admin where username=?",username);
        if(admin==null){
            throw new ServiceException("用户不存在");
        }
        String md5Pwd= SecureUtil.md5(password+ md5Key);
        System.out.println("password:"+md5Pwd);
        if(!md5Pwd.equals(admin.getStr("password"))){
            throw new ServiceException("密码错误");
        }
        admin.set("login_time",new Date());
        admin.set("login_ip", IpUtils.getIpAddr());
        Db.update("sys_admin", admin);
        String key= Jboot.configValue("yminfo.jwtkey");
        String expireTime= Jboot.configValue("yminfo.jwtExpireTime");
        String token= AdminTokenUtils.genToken(admin.getLong("id"),key, Integer.valueOf(expireTime));
        return token;
    }
    public List<SysMenu> getMenuTree(Integer adminId){
        List<SysUserRole> sysUserRoles=sysUserRoleService.findListByColumns(Columns.create("admin_id",adminId));
        return null;
    }
}
